package com.hdoit.apollo.web.wechat.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.billing.model.Billing;
import com.hdoit.apollo.logical.billing.service.IBillingService;
import com.hdoit.apollo.logical.cargo.mapper.CategoryMapper;
import com.hdoit.apollo.logical.cargo.model.Cargo;
import com.hdoit.apollo.logical.cargo.model.Category;
import com.hdoit.apollo.logical.cargo.model.Collocation;
import com.hdoit.apollo.logical.cargo.service.ICargoService;
import com.hdoit.apollo.logical.cargo.service.ICategoryService;
import com.hdoit.apollo.logical.cargo.service.ICollocationService;
import com.hdoit.apollo.logical.common.enums.billing.BillingConfirm;
import com.hdoit.apollo.logical.common.enums.billing.BillingState;
import com.hdoit.apollo.logical.common.enums.billing.PayState;
import com.hdoit.apollo.logical.common.enums.wechat.BuyStatus;
import com.hdoit.apollo.logical.shop.model.Customer;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.service.ICustomerService;
import com.hdoit.apollo.logical.shop.service.IShopService;
import com.hdoit.apollo.logical.stock.service.IStockService;
import com.hdoit.apollo.logical.viewmodel.cargo.CargoSearch;
import com.hdoit.apollo.logical.viewmodel.stock.OutStockCollocationInfo;
import com.hdoit.apollo.logical.viewmodel.wechat.BuyCarSearch;
import com.hdoit.apollo.logical.wechat.model.BuyCar;
import com.hdoit.apollo.logical.wechat.service.IBuyCarService;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.webpage.web.base.BaseWebpage;
import com.tennetcn.webpage.web.component.annotation.WebpageAuthMode;
import com.tennetcn.webpage.web.enums.WebpageAuthEnum;
import com.tennetcn.webpage.web.message.WechatLoginModel;

@Controller
@RequestMapping(value = "/wechat/shop/")
@WebpageAuthMode(validMode =WebpageAuthEnum.tryWechatAuth)
public class ShopController extends BaseWebpage{

	@Override
	public String getRoutePath() {
		return "areas/wechat/shop/";
	}
	
	@Autowired
	private IShopService shopService;
	
	@Autowired
	private ICargoService cargoService;
	
	@Autowired
	private ICollocationService collocationService;
	
	@Autowired
	private ICategoryService categoryService;
	
	@Autowired
	private CategoryMapper categoryMapper;
	
	@Autowired
	private IStockService stockService;
	
	@Autowired
	private ICustomerService customerService;
	
	@Autowired
	private IBuyCarService buyCarService;
	
	@Autowired
	private IBillingService billingService;
	
	
	
    private final String shopViewName="shop";
    private final String carViewName="car";
    private final String meViewName="me";
    private final String findViewName="find";
    private final String productViewName="product";
    private final String outputViewName="output";
    private final String outputForFindViewName="outputForFind";
    private final String getCargoInfoViewName="getCargoInfo";
    private final String saveViewName="save";
    private final String saveBillingViewName="saveBilling";
    
  
    @RequestMapping(value = saveBillingViewName, method = { RequestMethod.POST }, produces = "text/html;charset=UTF-8")
    public @ResponseBody String saveBilling(Model model,String nickName,String billingMoney,String collocationIds,String salePrices,String buyNums,String cargoIds,String shopId,String openId,String units,String customerId){
    	System.err.println(collocationIds+"胡茂树"+buyNums+"xxxx"+salePrices+"/////////"+cargoIds);
    	OutStockCollocationInfo outStockCollocationInfo=new OutStockCollocationInfo();
    	outStockCollocationInfo.setCargoId(cargoIds);
    	outStockCollocationInfo.setCollocationId(collocationIds);
    	outStockCollocationInfo.setRealPrice(salePrices);
    	outStockCollocationInfo.setCollocationNum(buyNums);
    	outStockCollocationInfo.setUnit(units);
    	Customer customer=new Customer();
    	if (StringUtils.isEmpty(customerId)) {
			customer.setCustomerId(CommonUtils.getKeyId());
			customer.setCustomerName(nickName);
			customer.setNickName(nickName);
			customer.setOpenId(openId);
            customer.setCreateDate(DateUtils.getCurrent());
            customer.setDeleteMark(YesOrNoInteger.no);
            customer.setModelStatus(ModelStatus.add);
            customer.setShopId(shopId);
            customerService.applyChange(customer);
		}else {
			customer=customerService.queryCustomerInfoByCustomerId(customerId);
		}
    	String[] collocationIdList=collocationIds.split(",");
    	for (String collocationId : collocationIdList) {
    		BuyCar buyCar=buyCarService.queryModelByCollocationIdAndShopId(collocationId,shopId);
    		if (!StringUtils.isEmpty(buyCar)) {
    			buyCar.setBuyStatus(BuyStatus.have);
        		buyCar.setModelStatus(ModelStatus.update);
        		buyCar.setModifyDate(DateUtils.getCurrent());
        		
        		buyCarService.applyChange(buyCar);
			}	
		}
    	Billing billing=new Billing();
    	
		if(StringUtils.isEmpty(billing.getBillingId())){
		        	
            billing.setBillingId(CommonUtils.getKeyId());
           
            billing.setCreateDate(DateUtils.getCurrent());
            billing.setDeleteMark(YesOrNoInteger.no);
            billing.setModelStatus(ModelStatus.add);
            billing.setShopId(shopId);
            billing.setCustomerId(customer.getCustomerId());
            billing.setBillingState(BillingState.notShipped);
            billing.setBillingMoney(Double.parseDouble(billingMoney));
            billing.setUnpaidAmount(billing.getBillingMoney());
            billing.setPayState(PayState.unpaid);
            billing.setConfirm(BillingConfirm.unCheck);
            
            String timestamp = DateUtils.convertDate2String("yyyyMMddHHmmss", DateUtils.getCurrent());
            billing.setBillingNo("WXD-"+timestamp);
            billing.setComment(" ");
        }else{
            billing.setModifyDate(DateUtils.getCurrent());
            billing.setModelStatus(ModelStatus.update);
        }
      

        if(billingService.applyBillingAndOutStock(billing,outStockCollocationInfo)){
        	
        	return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }else{
        	return new JsonActionResult(ManageContainer.ERROR).toJson();
        }

    }
    
    
    //@RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    @RequestMapping(value = saveViewName, method = { RequestMethod.POST }, produces = "text/html;charset=UTF-8")
    public @ResponseBody String save(Model model,String collocationIds,String buyNums,String shopId,String customerId){
    	System.err.println(collocationIds+"胡茂树"+buyNums+"xxxx"+shopId+"customerId"+customerId);
    	String[] collocationIdList=collocationIds.split(",");
    	String[] numList=buyNums.split(",");
    	List<BuyCar> buyCars=new ArrayList<BuyCar>();
    	for (int i = 0; i < numList.length; i++) {
    		BuyCar buyCar=new BuyCar();
    		 buyCar.setId(CommonUtils.getKeyId());
    		 buyCar.setCollocationId(collocationIdList[i]);
    		 buyCar.setBuyNum(Double.parseDouble(numList[i]));
             buyCar.setCreateDate(DateUtils.getCurrent());
             buyCar.setDeleteMark(YesOrNoInteger.no);
             buyCar.setBuyStatus(BuyStatus.will);
             buyCar.setModelStatus(ModelStatus.add);
             buyCar.setShopId(shopId);
             buyCar.setCustomerId(customerId);
             buyCars.add(buyCar);
		}

    		for (int i = 0; i < collocationIdList.length; i++) {
    			BuyCar buycared=buyCarService.queryModelByCollocationIdAndShopId(buyCars.get(i).getCollocationId(),buyCars.get(i).getShopId());
    			if (!StringUtils.isEmpty(buycared)) {
    				 buyCars.add(buycared);
    			}
    		}
	  	
    	//合并相同数据
    	List<BuyCar> buyCarsList=new ArrayList<BuyCar>();
		
		HashMap<String, BuyCar> map=new HashMap<String, BuyCar>();
		
		for (BuyCar bcCar : buyCars) {
			String id=bcCar.getCollocationId();
			if (map.containsKey(id)) {
				Double number=map.get(id).getBuyNum();
				number+=bcCar.getBuyNum();
				map.get(id).setBuyNum(number);
				String ids=bcCar.getId();
				
				BuyCar buyCar=buyCarService.queryModel(ids);
				if (!StringUtils.isEmpty(buyCar)) {
					map.get(id).setId(buyCar.getId());
					map.get(id).setModifyDate(DateUtils.getCurrent());
					map.get(id).setModelStatus(ModelStatus.update);
				}
			}else {
				map.put(id, bcCar);
				
			}
			
		}
		
		Iterator<Entry<String, BuyCar>> iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			buyCarsList.add(iter.next().getValue());
		}
		
    	
        if(buyCarService.applyChanges(buyCarsList)){
        	return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }else{
        	return new JsonActionResult(ManageContainer.ERROR).toJson();
        }

    }
    
    @RequestMapping(value = productViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String product(Model model,String cargoId,String searchMark){
    	System.err.println(searchMark+"类型");
    	Cargo cargo=cargoService.queryModelForView(cargoId);
    	Shop shop=shopService.queryModel(cargo.getShopId());
    	List<Collocation> collocations=new ArrayList<Collocation>();
    	collocations=collocationService.queryListForWechatByCargoId(cargoId,cargo.getShopId());
    	CargoSearch search=new CargoSearch();
    	if (!StringUtils.isEmpty(searchMark)) {
    		search.setCategoryName(cargo.getCategoryName());
		}
    	
    	search.setShopId(cargo.getShopId());
    	List<Cargo> cargos=cargoService.queryListMPForWechat(search, null);
		model.addAttribute("cargo", cargo);
		model.addAttribute("collocations", collocations);
		model.addAttribute("cargos", cargos);
		model.addAttribute("shop", shop);
		model.addAttribute("searchMark", searchMark);
        return view(productViewName);
    }
    
    @RequestMapping(value = carViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String car(Model model,String shopId,String searchMark){
    	if (webpageSession.getCurrentLogin()!=null) {
    		WechatLoginModel wechatLoginModel=webpageSession.getCurrentLogin().getWechatLoginModel();
			String openId=wechatLoginModel.getOpenId();
			
			Customer customer=customerService.queryModelByOpenId(openId,shopId);
			
			
			if (StringUtils.isEmpty(customer)&&!StringUtils.isEmpty(openId)) {
				Customer customered=new Customer();
				customered.setCustomerId(CommonUtils.getKeyId());
				customered.setCustomerName(wechatLoginModel.getNickName());
				customered.setNickName(wechatLoginModel.getNickName());
				customered.setOpenId(openId);
				customered.setCreateDate(DateUtils.getCurrent());
				customered.setDeleteMark(YesOrNoInteger.no);
				customered.setModelStatus(ModelStatus.add);
				customered.setShopId(shopId);
				
				customerService.applyChange(customered);
				customer=customerService.queryModelByOpenId(openId,shopId);
			}
			
			model.addAttribute("customer", customer);
			model.addAttribute("wechatLoginModel", wechatLoginModel);
			System.err.println(openId+"胡茂树");
		}
    	
    	
    	BuyCarSearch search=new BuyCarSearch();
    	
    	if (!StringUtils.isEmpty(shopId)) {
			search.setShopId(shopId);
		}
    	
    	List<BuyCar> buyCars=buyCarService.queryListMP(search, null);
    	model.addAttribute("buyCars", buyCars);
    	model.addAttribute("shopId", shopId);
    	model.addAttribute("searchMark", searchMark);
    	
        return view(carViewName);
    }
	
    @RequestMapping(value = shopViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String shop(Model model, String shopId,String searchMark,String searchKey,String pageIndex,String pageSize, boolean ajaxPost){
    	
    	if (webpageSession.getCurrentLogin()!=null) {
    		WechatLoginModel wechatLoginModel=webpageSession.getCurrentLogin().getWechatLoginModel();
			String openId=wechatLoginModel.getOpenId();
			
			Customer customer=customerService.queryModelByOpenId(openId,shopId);
			
			if (StringUtils.isEmpty(customer)&&!StringUtils.isEmpty(openId)) {
				Customer customered=new Customer();
				customered.setCustomerId(CommonUtils.getKeyId());
				customered.setCustomerName(wechatLoginModel.getNickName());
				customered.setNickName(wechatLoginModel.getNickName());
				customered.setOpenId(openId);
				customered.setCreateDate(DateUtils.getCurrent());
				customered.setDeleteMark(YesOrNoInteger.no);
				customered.setModelStatus(ModelStatus.add);
				customered.setShopId(shopId);
				
				customerService.applyChange(customered);
				customer=customerService.queryModelByOpenId(openId,shopId);
			}
			model.addAttribute("customer", customer);
			model.addAttribute("wechatLoginModel", wechatLoginModel);
		}
    	if (StringUtils.isEmpty(shopId)) {
    		shopId="81182a17-0f4f-4228-b9e8-6372cb8c522d";
		}
    	Shop shop=shopService.queryModel(shopId);
    	if (StringUtils.isEmpty(pageIndex)) {
    		pageIndex="1";
		}
    	if (StringUtils.isEmpty(pageSize)) {
    		 pageSize="20";
		}

    	CargoSearch search=new CargoSearch();
    	if (!StringUtils.isEmpty(searchKey)) {
			search.setSearchKey(searchKey);
		}
    	PagerModel pagerModel=null;
    	if(pageSize!=""){
    		pagerModel = new PagerModel(Integer.parseInt(pageSize), Integer.parseInt(pageIndex));
    	}else{
    		pagerModel=new PagerModel();
    		pagerModel.setPageSize(20);
    	}
    	//按品类分享查询标记
    	if (!StringUtils.isEmpty(searchMark)) {
			search.setCategoryName(searchMark);
			model.addAttribute("shop", shop);
		}
    	search.setShopId(shopId);
    	List<Cargo> cargos=cargoService.queryListMPForWechat(search, pagerModel);
    	
    	if (!StringUtils.isEmpty(searchMark)) {
			model.addAttribute("searchMark", searchMark);
		}
    	model.addAttribute("shop", shop);
    	model.addAttribute("cargos", cargos);
    	 
    	if(ajaxPost){
            return view(outputViewName);
        }
    	 
        return view(shopViewName);
    }
    
    @RequestMapping(value = meViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String me(Model model,String shopId,String searchMark){
    	if (webpageSession.getCurrentLogin()!=null) {
    		WechatLoginModel wechatLoginModel=webpageSession.getCurrentLogin().getWechatLoginModel();
			String openId=wechatLoginModel.getOpenId();
			System.err.println(openId+"微信");
			Customer customer=customerService.queryModelByOpenId(openId,shopId);
			
			if (StringUtils.isEmpty(customer)&&!StringUtils.isEmpty(openId)) {
				Customer customered=new Customer();
				customered.setCustomerId(CommonUtils.getKeyId());
				customered.setCustomerName(wechatLoginModel.getNickName());
				customered.setNickName(wechatLoginModel.getNickName());
				customered.setOpenId(openId);
				customered.setCreateDate(DateUtils.getCurrent());
				customered.setDeleteMark(YesOrNoInteger.no);
				customered.setModelStatus(ModelStatus.add);
				customered.setShopId(shopId);
				
				customerService.applyChange(customered);
				customer=customerService.queryModelByOpenId(openId,shopId);
			}
			model.addAttribute("customer", customer);
			model.addAttribute("wechatLoginModel", wechatLoginModel);
		}
    	
    	if (StringUtils.isEmpty(shopId)) {
    		shopId="81182a17-0f4f-4228-b9e8-6372cb8c522d";
		}   	
    	Shop shop=shopService.queryModel(shopId);
    	model.addAttribute("shop", shop);
    	model.addAttribute("searchMark", searchMark);
    	 
        return view(meViewName);
    }
    
    @RequestMapping(value = findViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String find(Model model,String shopId,String searchMark,String searchKey,String categoryName,String pageIndex,String pageSize, boolean ajaxPost ){
    	if (StringUtils.isEmpty(shopId)) {
    		shopId="81182a17-0f4f-4228-b9e8-6372cb8c522d";
		}
    	
    	Shop shop=shopService.queryModel(shopId);
    	List<Category> categories=categoryMapper.queryListForWechat(shopId);
    	if (StringUtils.isEmpty(pageIndex)) {
    		pageIndex="1";
		}
    	if (StringUtils.isEmpty(pageSize)) {
    		 pageSize="20";
		}
    	
    	CargoSearch search=new CargoSearch();
    	if (!StringUtils.isEmpty(searchKey)) {
			search.setSearchKey(searchKey);
		}
    	if (!StringUtils.isEmpty(searchMark)) {
			search.setCategoryName(searchMark);
		}else {
			search.setCategoryName(categoryName);
		}

    	PagerModel pagerModel=null;
    	if(pageSize!=""){
    		pagerModel = new PagerModel(Integer.parseInt(pageSize), Integer.parseInt(pageIndex));
    	}else{
    		pagerModel=new PagerModel();
    		pagerModel.setPageSize(20);
    	}
    	
    	search.setShopId(shopId);
    	
    	List<Cargo> cargos=cargoService.queryListMPForWechat(search, pagerModel);
    	
    	if (webpageSession.getCurrentLogin()!=null) {
    		WechatLoginModel wechatLoginModel=webpageSession.getCurrentLogin().getWechatLoginModel();
    		System.err.println(wechatLoginModel.getHeadImgUrl()+"头像图片地址");
			String openId=wechatLoginModel.getOpenId();
			System.err.println(openId+"微信");
			Customer customer=customerService.queryModelByOpenId(openId,shopId);
			
			if (StringUtils.isEmpty(customer)&&!StringUtils.isEmpty(openId)) {
				Customer customered=new Customer();
				customered.setCustomerId(CommonUtils.getKeyId());
				customered.setCustomerName(wechatLoginModel.getNickName());
				customered.setNickName(wechatLoginModel.getNickName());
				customered.setOpenId(openId);
				customered.setCreateDate(DateUtils.getCurrent());
				customered.setDeleteMark(YesOrNoInteger.no);
				customered.setModelStatus(ModelStatus.add);
				customered.setShopId(shopId);
				
				customerService.applyChange(customered);
				customer=customerService.queryModelByOpenId(openId,shopId);
			}
			model.addAttribute("customer", customer);
		}
    	
    	 model.addAttribute("shop", shop);
    	 model.addAttribute("cargos", cargos);
    	 model.addAttribute("categories", categories);
    	 model.addAttribute("searchMark", searchMark);
    	 if(ajaxPost){
             return view(outputForFindViewName);
         }
        return view(findViewName);
    }
    
    @RequestMapping(value = getCargoInfoViewName, method = { RequestMethod.GET},produces = "text/html;charset=UTF-8")
    public @ResponseBody String getCargoInfo(Model model,String cargoId,String shopId){
    	
    	List<Collocation> collocations=collocationService.queryListForWechatByCargoId(cargoId, shopId);
        return "{\"data\":"+JsonUtils.writeValueAsString(collocations)+"}";
    }
}
